package com.shitou.springai1.user.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.shitou.springai1.user.entity.ConversationRequest;
import com.shitou.springai1.user.entity.MessageType;
import com.shitou.springai1.user.entity.StreamResponseMessage;
import com.shitou.springai1.user.service.EnhancedChatService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.UUID;

@RestController
@PreAuthorize("hasRole('USER')")
@RequestMapping("/api/user")
@Slf4j
public class EnhancedChatController {

    @Autowired
    private EnhancedChatService enhancedChatService;

    /**
     * 增强的流式聊天接口（支持记忆功能）
     */
    @PostMapping(value = "/chat/stream", produces = MediaType.APPLICATION_NDJSON_VALUE)
    public Flux<StreamResponseMessage> enhancedStreamChat(@RequestBody ConversationRequest request,
                                                          HttpServletResponse response) {
        response.setCharacterEncoding("utf-8");

        if (StringUtils.isBlank(request.getQuestion())) {
            return Flux.just(new StreamResponseMessage(
                MessageType.ERROR, "问题不能为空", null, LocalDateTime.now()
            ));
        }

        // 确保有sessionId
        if (StringUtils.isBlank(request.getSessionId())) {
            request.setSessionId(UUID.randomUUID().toString().substring(0, 8));
        }

        log.info("接收增强流式聊天请求: session={}, question={}",
                request.getSessionId(), request.getQuestion());

        return enhancedChatService.enhancedStreamChat(request, response);
    }

    /**
     * 兼容旧接口
     */
//    @PostMapping(value = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
//    public Flux<String> legacyChatStream(@RequestBody Map<String, String> body,
//                                        HttpServletResponse response) {
//        response.setCharacterEncoding("utf-8");
//
//        String question = body.getOrDefault("question", "");
//        String sessionId = body.getOrDefault("sessionId",
//                        UUID.randomUUID().toString().substring(0, 8));
//
//        ConversationRequest request = new ConversationRequest();
//        request.setQuestion(question);
//        request.setSessionId(sessionId);
//        request.setIncludeImages(true);
//
//        log.info("接收旧版流式聊天请求: session={}, question={}", sessionId, question);
//
//        // 将结构化响应转换为纯文本流
//        return enhancedChatService.enhancedStreamChat(request, response)
//                .map(this::convertToLegacyFormat);
//    }

    /**
     * 获取会话信息
     */
    @GetMapping("/chat/session/{sessionId}")
    public ResponseEntity<Map<String, Object>> getSessionInfo(@PathVariable String sessionId) {
        try {
            Map<String, Object> sessionInfo = enhancedChatService.getSessionInfo(sessionId);
            System.out.println("回话id"+sessionInfo);
            return ResponseEntity.ok(sessionInfo);
        } catch (Exception e) {
            log.error("获取会话信息失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("error", e.getMessage()));
        }
    }

    /**
     * 清除会话记忆
     */
    @DeleteMapping("/chat/session/{sessionId}")
    public ResponseEntity<Map<String, Object>> clearSession(@PathVariable String sessionId) {
        try {
            enhancedChatService.clearSessionMemory(sessionId);
            return ResponseEntity.ok(Map.of("message", "会话记忆已清除", "sessionId", sessionId));
        } catch (Exception e) {
            log.error("清除会话记忆失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("error", e.getMessage()));
        }
    }

    /**
     * 获取记忆统计
     */
    @GetMapping("/chat/memory/stats")
    public ResponseEntity<Map<String, Object>> getMemoryStats() {
        // 这个方法需要添加到ConversationMemoryService中
        return ResponseEntity.ok(Map.of("stats", "待实现"));
    }

    /**
     * 将结构化消息转换为旧版纯文本格式
     */
    private String convertToLegacyFormat(StreamResponseMessage message) {
        switch (message.getType()) {
            case TEXT_CHUNK:
                return message.getContent(); // 直接返回文本内容
            case IMAGE_DATA:
                // 对于图片信息，返回一个特殊的标记
                return "\n[图片信息已找到，请查看侧边栏]\n";
            case SEARCH_RESULT:
                return "\n[搜索完成: " + message.getContent() + "]\n";
            case ERROR:
                return "\n[错误: " + message.getContent() + "]\n";
            case COMPLETE:
                return ""; // 完成信号
            default:
                return "";
        }
    }
    }
